package dai.noui

import dai.core.base.MyLog
import dai.core.base.ShaderProgram
import dai.core.base.Utils
import org.lwjgl.glfw.GLFW.*
import v1.Obj
import v1.ObjLoader
import v1.Scene
import kotlin.math.abs

class V1Scene : Scene() {

    var preX = 0f
    var preY = 0f

    companion object{
        const val ControlScala = 0.01f
    }

    override fun initScene() {

        val shaderProgram = ShaderProgram()

        // init shader
        val vertexSource = Utils.loadShader("/v1.vs.shader")
        val fragSource = Utils.loadShader("/v1.fs.shader")
        shaderProgram.initShader(vertexSource, fragSource)
        shaderProgram.createUniform("projectMatrix")
        shaderProgram.createUniform("modelViewMatrix")

        // init mesh
        val mesh = ObjLoader.loadMesh("/models/bunny.obj")

        // 往场景中添加东西
        val cube = Obj()
        cube.position.z = -3f
        cube.renderItem = CubeRender(shaderProgram, mesh)
        add(cube)

        val cube2 = Obj()
        cube2.position.x = 2f
        cube2.renderItem = CubeRender(shaderProgram, mesh)
        add(cube2)
    }

    override fun input() {

        val inputMgr = app.window.inputMgr
        val keyboardMgr = inputMgr.keyboardMgr

        // keyboard
        keyboardMgr.keyDown { keycode ->
            //MyLog.info("keycode:$keycode  down!")
            when (keycode) {
                GLFW_KEY_ESCAPE -> glfwSetWindowShouldClose(inputMgr.window.winHandle, true)
                GLFW_KEY_A -> MyLog.info("a 按下....")
            }
        }
        keyboardMgr.keyUp { keycode ->
            //MyLog.info("keycode:$keycode up!")
        }

        // mouse
        val mouseMgr = inputMgr.mouseMgr
        mouseMgr.mouseBegin { button, xpos, ypos ->
            if (button == GLFW_MOUSE_BUTTON_LEFT) {
                //MyLog.info("down x:$xpos,y:$ypos")
                preX = xpos
                preY = ypos
            }
        }
        mouseMgr.mouseMove { button, xpos, ypos ->
            if (button == GLFW_MOUSE_BUTTON_LEFT) {
                //MyLog.info("move x:$xpos,y:$ypos")
                val camera = app.camera
                val dx = xpos - preX
                val dy = ypos - preY
                preX = xpos
                preY = ypos
                if (abs(dx) - abs(dy) > 0){
                    //  横向移动
                    camera.translateX(dx * ControlScala)
                }else{
                    // 垂直方向,
                    camera.translateY(dy * ControlScala)
                }
            }
        }
        mouseMgr.mouseEnd { button, xpos, ypos ->
            if (button == GLFW_MOUSE_BUTTON_LEFT) {
                MyLog.info("end x:$xpos,y:$ypos")
            }
        }
    }

    override fun update() {
    }
}